package com.sdx.console.contract.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.itextpdf.text.DocumentException;
import com.sdx.console.common.entity.BaseProvince;
import com.sdx.console.contract.backstage.Utils.InvoiceUtils;
import com.sdx.console.contract.backstage.Utils.Utils;
import com.sdx.console.contract.backstage.Utils.provinceValue;
import com.sdx.console.contract.entity.*;
import com.sdx.console.contract.entity.ContractMember;
import com.sdx.console.contract.service.ContractInfoService;
import com.sdx.console.entity.CustomerAccount;
import com.sdx.console.utils.EDateUtil;
import com.sdx.service.ConfigService;
import org.apache.commons.collections.map.HashedMap;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.sdx.console.contract.backstage.Utils.MD5;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 合同 Controller 类
 */
@Controller
@RequestMapping("/invoice")
public class InvoiceController extends AuthorizedBaesController {

    private static final String DBName = "coredb";//数据库名称

    private static final String PASSWD_SALT = "owrhgow38";

    private static boolean isSave = true;//如果开始回滚，则不进行插入 也不生成pdf文件

//    private  final String destPath ="C:/Users/Administrator/Desktop/pdf/搬功能";

    @Resource
    private SQLManager sqlManager;

    @Resource
    private ContractInfoService contractInfoService;

    private static ContractAllInfo thisContractAllInfo = null ;

    /**
     * 添加订单
     */
    @RequestMapping(value = "/add.json",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public  String addIncoice(@RequestBody String json, HttpServletRequest request) throws ParseException {

        String destPath = ConfigService.contractfile;

        ContractAllInfo contractAllInfo= toEntity(json);
        thisContractAllInfo = contractAllInfo;

        //通用数据
        CoreUser user = getLoginUser(request); //当前用户用户id
        Date createDate = new EDateUtil().getNowDate();//当前时间
        Map<Integer, Integer> fwlist  = contractAllInfo.getFw();//服务数组
        Map<String, Integer> tuifei  = contractAllInfo.getTuifei();//退费
        Map<String, Integer> OtherFw = contractAllInfo.getOtherFw();//论文和竞赛
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String invoice_no = sdf.format(new Date());//合同号
        List<Map<Integer,Integer>> listfw = new ArrayList<>() ;//为了给生成合同订单的方法使用

        LambdaQuery<CoreUser> coreuser =  sqlManager.lambdaQuery(CoreUser.class);
        //判断学生信息是不是咨询师账号
        if(contractAllInfo.getStudentPhone() != null){
            long num1 = coreuser.andEq("code",contractAllInfo.getStudentPhone()).count();
            if (num1>0){
                return "警告，学生信息不能填内部员工的手机号！";
            }
        }
        //判断订单是否已存在
        if (sqlManager.lambdaQuery(ContractInfo.class)
                .andEq("student_phone",contractAllInfo.getStudentPhone())
                .andNotEq("ht_status","3")
                .count()>0){
            return "学生 "+contractAllInfo.getStudentName()+" 订单已存在，请查询是否存在后再提交";
        }

        //新增判断是不是已有的会员
        if(sqlManager.lambdaQuery(CustomerAccount.class).andEq("reg_account",contractAllInfo.getStudentPhone()).count()>0){
            //判断是否需要升级为龙卡用户，如果否更新日期
            //先拿到CustomerId 然后在根据customerid判断是不是龙卡用户
            List<CustomerAccount> ListcustomerAccounts = sqlManager.lambdaQuery(CustomerAccount.class).andEq("reg_account",contractAllInfo.getStudentPhone()).select();
            if (ListcustomerAccounts.size()==1 ){
                String customerId =ListcustomerAccounts.get(0).getCustomerId();
                List<RightCustomerRole> rightCustomerRoleList = sqlManager.lambdaQuery(RightCustomerRole.class).andEq("customer_id",customerId).select();
                if(rightCustomerRoleList.size()>0){//是龙卡 然后判断是否需要更新过期是按

                    Date newExpiredDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(contractAllInfo.getFwYear()+"-08-31 23:59:59");
                    RightCustomerRole newrightCustomerRole = rightCustomerRoleList.get(0);//当前用户的龙卡信息
                    Date oldExpiredDate = rightCustomerRoleList.get(0).getExpiredDate();
                    if(oldExpiredDate==null || oldExpiredDate.equals("null")){
                        newrightCustomerRole.setExpiredDate(newExpiredDate);//更新过期日期
                        sqlManager.updateById(newrightCustomerRole);
                    }else{
                        if (newExpiredDate.after(oldExpiredDate) ){
                            newrightCustomerRole.setExpiredDate(newExpiredDate);//更新过期日期
                            sqlManager.updateById(newrightCustomerRole);
                        }
                    }


                }else{
                    //不是龙卡，创建龙卡用户
                    InsertLongKa(customerId);
                }

            }

        }
        else{
            try {
                /**
                 * 创建普通会员账号 会员账号表
                 */
                String passwd = "123456";
                passwd = MD5.MD5Encode(PASSWD_SALT+MD5.MD5Encode(passwd));//密码
                String customerid = Utils.uuid();//用户id;

                CustomerAccount customerAccount = new CustomerAccount();
                customerAccount.setTenantId(0);
                customerAccount.setCustomerId(customerid);//用户id
                customerAccount.setRegType("c");//账号类型 a、微信小程序， b、h5微信，c、手机号（短信码验证），d、手机唯一识别码（app），e、合作app接入，f、百度小程序，g、直接登录,t、头条小程序登录，h、qq号，p、手机号和密码方式
                customerAccount.setRegAccount(contractAllInfo.getStudentPhone());//学生手机号
                customerAccount.setPasswd(passwd);//密码
                customerAccount.setRegTime(createDate);//注册时间
                customerAccount.setAccountStatus(1);
                sqlManager.insertTemplate(customerAccount);//插入 用户账号密码信息表
                /**
                 *  插入普通会员的信息， 省份，文理科 ，高考年份 等等。。 会员基础信息表
                 */
                CustomerInfo customerInfo = new CustomerInfo();
                customerInfo.setCustomerId(customerid);//用户id
                customerInfo.setCustomerName(contractAllInfo.getStudentName());//真名
                customerInfo.setAddress(contractAllInfo.getStudentAddress());//住址
                customerInfo.setProvinceId(provinceValue.getcode(contractAllInfo.getStudentProvince()));//用户省份
                if ("文科".equals(contractAllInfo.getStudentMajorType())){
                    customerInfo.setMajorType(1);//文理科
                }else{
                    customerInfo.setMajorType(2);//文理科
                }
                customerInfo.setChoiceYear(Integer.valueOf(contractAllInfo.getFwYear()));//服务年份
                customerInfo.setRegType("c");
                customerInfo.setSourceId(contractAllInfo.getStudentPhone());//来源id
                customerInfo.setModule("15");//来源模块 14、公开课，15、圣达信教育，16、志愿填报，17、自主招生，18、艺考生
                customerInfo.setChannel("sdx");//来源渠道
                customerInfo.setPhone(contractAllInfo.getStudentPhone());//绑定手机号
                customerInfo.setIsTeacher(0);
                customerInfo.setCustStatus(1);
                customerInfo.setRegisterTime(createDate);
                if ("男".equals(contractAllInfo.getStudentSex())){
                    customerInfo.setSex(1);
                }else{
                    customerInfo.setSex(0);
                }
                customerInfo.setHighProvinceId(provinceValue.getcode(contractAllInfo.getStudentProvince()));//大学地址
                String citysql = "SELECT * FROM base_city WHERE city_name='"+contractAllInfo.getStudentCity()+"'";

                int cityId =sqlManager.execute(new SQLReady(citysql), BaseCity.class).get(0).getCityId();
                customerInfo.setHighCityId(cityId);//市


                String boroghsql = "SELECT * FROM base_borough WHERE borough_name='"+contractAllInfo.getStudentBorough()+"'";
                int boroughId = sqlManager.execute(new SQLReady(boroghsql), BaseBorough.class).get(0).getBoroughId();
                customerInfo.setHighBoroughId(boroughId);//区

                try {
                    int schoolId = sqlManager.lambdaQuery(BaseSchool.class).andEq("school_name",contractAllInfo.getStudentSchool()).single().getId();
                    customerInfo.setHighSchoolId(schoolId);//高中学校id，有可能数据库里没有这个学校的id 还没考虑怎么写
                } catch (Exception e) {

                }

                sqlManager.insertTemplate(customerInfo);

                /**
                 * 插入龙卡信息
                 */
                InsertLongKa(customerid);



            } catch (Exception e) {
                System.out.println("入库失败！ 开始回滚");
                isSave = false;//是否需要生成pdf 和保存数据
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }

        /**
         * 不管是否 插入会员  都必须插入合同的信息
         */

        /**
         * 插入合同信息
         */
        ContractInfo contractInfo = new ContractInfo();
        contractInfo.setInvoiceNo(invoice_no);
        contractInfo.setCustomerName(contractAllInfo.getParentName());//家长名称
        contractInfo.setCustomerPhone(contractAllInfo.getParentPhone());//家长手机号
        contractInfo.setCustomerIdcard(contractAllInfo.getParentIDCard());//家长身份证
        contractInfo.setStudentName(contractAllInfo.getStudentName());//学生姓名
        contractInfo.setStudentPhone(contractAllInfo.getStudentPhone());//学生手机号
        contractInfo.setGraduateYear(Integer.valueOf(contractAllInfo.getFwYear()));//高考年份
        contractInfo.setSeller(contractAllInfo.getSigningTeacher());//签单老师
        contractInfo.setServant(contractAllInfo.getFwTeacher());//服务老师

        JSONObject SchoolExt = new JSONObject();
        SchoolExt.put("prov",contractAllInfo.getStudentProvince());
        SchoolExt.put("city",contractAllInfo.getStudentCity());
        SchoolExt.put("borough",contractAllInfo.getStudentBorough());
        SchoolExt.put("school",contractAllInfo.getStudentSchool());
        SchoolExt.put("grade",contractAllInfo.getStudentGrade());
        SchoolExt.put("classes",contractAllInfo.getStudentClass());
        SchoolExt.put("gender",contractAllInfo.getStudentSex());
        SchoolExt.put("majorType",contractAllInfo.getStudentMajorType());
        contractInfo.setSchoolExt(SchoolExt.toString());//学生信息

        //退费
        JSONObject tuifeiObj = new JSONObject();
        tuifeiObj.put("refund1",tuifei.get("tuifei1"));
        tuifeiObj.put("refund2",tuifei.get("tuifei2"));
        tuifeiObj.put("refund3",tuifei.get("tuifei3"));
        tuifeiObj.put("trans",String.valueOf(contractAllInfo.isToZhiYuan()));
        contractInfo.setRefundExt(tuifeiObj.toString());
        contractInfo.setOpenTicket(Integer.valueOf(contractAllInfo.getOpen_ticket()));//发票、
        //合同总金额
        int allnum = 0;
        for (Integer key : fwlist.keySet()){
            allnum += fwlist.get(key);
        }
        //论文和奖项
        for (Map.Entry<String,Integer> entry : contractAllInfo.getOtherFw().entrySet() ){
            if ("prize".equals(entry.getKey()) ){//不算论文的费用 只算奖项
                if (entry.getValue() >0 ){
                    allnum += entry.getValue();
                }
            }
        }
        contractInfo.setContractAmt(BigDecimal.valueOf(allnum));
        contractInfo.setUrlPdf(destPath+"/"+invoice_no+"/"+invoice_no+".pdf");
        contractInfo.setHtStatus(0);//合同状态
        contractInfo.setFkStatus(0);//付款状态
        contractInfo.setFwStatus(0);//服务状态
        contractInfo.setTkStatus(0);//退款状态
        contractInfo.setCreateDate(createDate);//创建时间
        contractInfo.setRemark(contractAllInfo.getReamark());//服务备注
        //更新人。。。 更新人名称 ..更新时间
        contractInfo.setUpdatedBy(user.getId().intValue());
        contractInfo.setUpdatedName(user.getName());
        contractInfo.setUpdatedTime(new EDateUtil().getNowDate());
        sqlManager.insertTemplate(contractInfo);

        /**
         * 插入服务团队
         */
        //根据合同号查询合同id
        Integer ContractId = sqlManager.lambdaQuery(ContractInfo.class).andEq("invoice_no",invoice_no).select().get(0).getContractId();
        List<com.sdx.console.customer.entity.CustomerInfo> list = contractInfoService.selectCustomerInfo("'"+contractAllInfo.getFwTeam().replaceAll(",","','")+"'");
        List<ContractMember> memberList = new ArrayList<>();
        for (com.sdx.console.customer.entity.CustomerInfo info:list) {
            ContractMember member = new ContractMember();
            member.setContractId(ContractId);//合同id号
            member.setUserId(info.getCustomerId());
            member.setUserName(info.getCustomerName());
            memberList.add(member);
        }
        if(memberList.size()>0){
            contractInfoService.insertContractMember(memberList);
        }
        /**
         * 插入合同的类型及费用
         */
        List<ContractPrices> listContractPrices = new ArrayList<>();
        for (Map.Entry<Integer,Integer> entry : fwlist.entrySet()){
            ContractPrices contractPrices = new ContractPrices();
            int typeid = entry.getKey();
            int money = entry.getValue();
            String value ="";
            switch (typeid){
                case 1 : value = "自主招生";break;
                case 2 : value = "志愿填报";break;
                case 3 : value = "港澳台申请";break;
                case 4 : value = "自主招生(保过)";break;
                case 5 : value = "综合素质评价";break;
                case 6 : value = "其他";break;
                case 7 : value = "论文";break;
                case 8 : value = "奖项";break;
            }
            contractPrices.setContractId(ContractId);
            contractPrices.setTypeId(typeid);
            contractPrices.setTypeName(value);
            contractPrices.setFee(money);
            listContractPrices.add(contractPrices);
        }
        //论文和奖项在另外一个里面
        Map<String,Integer> otherMap = contractAllInfo.getOtherFw();
        for (Map.Entry<String,Integer> entry : otherMap.entrySet()){
            if (entry.getValue() > 0 ){
                ContractPrices contractPrices = new ContractPrices();
                switch (entry.getKey()){
//                    case "dissertation":  论文不再使用，
//                        contractPrices.setTypeId(7);
//                        contractPrices.setTypeName("论文");
//                        contractPrices.setFee(entry.getValue());
//                        break;
                    case "prize":
                        contractPrices.setContractId(ContractId);
                        contractPrices.setTypeId(8);
                        contractPrices.setTypeName("奖项");
                        contractPrices.setFee(entry.getValue());
                        listContractPrices.add(contractPrices);
                        break;
                }

            }
        }
        sqlManager.insertBatch(ContractPrices.class,listContractPrices);


        //先生成电子合同，生成成功后，再插入表里
        //先判断是否有保过
        if (isSave){
            InvoiceUtils invoiceUtils = new InvoiceUtils();
            boolean BaoGuo = false;
            for (Map.Entry<Integer,Integer> entry : fwlist.entrySet()){

                Map<Integer,Integer> map = new HashedMap();
                map.put(entry.getKey(),entry.getValue());
                listfw.add(map);
                if (entry.getKey() == 4){
                    BaoGuo= true;
                }
            }
            try {
                //签单老师
                String singningTeacher  =  sqlManager.query(CustomerInfo.class).andEq("is_teacher","1").andEq("customer_id",contractAllInfo.getSigningTeacher()).select().get(0).getCustomerName();
                singningTeacher = singningTeacher.replaceAll(".*-", "");
                if (BaoGuo){
                    invoiceUtils.getPdfBaoguo(tuifei.get("tuifei1"),tuifei.get("tuifei2"),tuifei.get("tuifei3")
                            ,contractAllInfo.isToZhiYuan(),OtherFw.get("prize"),OtherFw.get("dissertation")
                            ,contractAllInfo.getStudentName(),contractAllInfo.getStudentSchool(),contractAllInfo.getStudentClass()
                            ,contractAllInfo.getStudentIDCard(),contractAllInfo.getStudentAddress(),contractAllInfo.getStudentPostal()
                            ,contractAllInfo.getStudentPhone(),contractAllInfo.getParentName(),contractAllInfo.getParentIDCard(),contractAllInfo.getParentPhone()
                            ,listfw,singningTeacher,invoice_no,destPath);
                }else{
                    invoiceUtils.getPdfNoBaoguo(tuifei.get("tuifei1"),tuifei.get("tuifei2"),tuifei.get("tuifei3")
                            ,contractAllInfo.isToZhiYuan(),OtherFw.get("prize"),OtherFw.get("dissertation")
                            ,contractAllInfo.getStudentName(),contractAllInfo.getStudentSchool(),contractAllInfo.getStudentClass()
                            ,contractAllInfo.getStudentIDCard(),contractAllInfo.getStudentAddress(),contractAllInfo.getStudentPostal()
                            ,contractAllInfo.getStudentPhone(),contractAllInfo.getParentName(),contractAllInfo.getParentIDCard(),contractAllInfo.getParentPhone()
                            ,listfw,singningTeacher,invoice_no,destPath);
                }
            } catch (Exception e) {
                e.printStackTrace();
                isSave = false;//是否需要生成pdf 和保存数据
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "生成合同失败！请联系客服";
            }
        }

        String result = "";
        if (isSave){
            result="成功生成合同";
        }else {
            result="生成合同失败，！请联系客服";
        }
        return result;

    }

    //升级为龙卡  时间转换异常向外抛
    public  String InsertLongKa(String customerid) throws ParseException {
        List<RightCustomerRole> rightCustomerRoleList = sqlManager.lambdaQuery(RightCustomerRole.class).andEq("customer_id",customerid).select();
        if (rightCustomerRoleList.size()>0){
            return "error";
        }else{
            RightCustomerRole rightCustomerRole = new RightCustomerRole();
            rightCustomerRole.setCustomerId(customerid);
            rightCustomerRole.setRoleId(1); //设置角色id 。
            rightCustomerRole.setRightStatus(2);//2、待激活，1、有效，0、失效 暂不清楚设置什么
            rightCustomerRole.setOnceOnly(0);
            //设置过期时间为 合同信息里的高考年份的8月31日 为过期时间

            String str = thisContractAllInfo.getFwYear()+"-08-31 23:59:59".toString();//
            rightCustomerRole.setExpiredDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str));//权限有效期

            rightCustomerRole.setCreateTime(new EDateUtil().getNowDate());
            rightCustomerRole.setRightSource(5);//1、支付购买；2、n码激活体验卡；3、龙卡激活，4、n码激活会员卡 5、一对一合同入单生成的会员
            rightCustomerRole.setRemark("一对一合同入单生成的会员");
            sqlManager.insert(rightCustomerRole);
        }
        return "success";

    }


    //把页面传过来的数据转成实体类
    public  ContractAllInfo  toEntity(String json){
        ContractAllInfo contractAllInfo = new ContractAllInfo();
        JSONObject jsonObject =  JSONObject.parseObject(json);

        contractAllInfo.setStudentName(jsonObject.getString("studentName"));
        contractAllInfo.setStudentIDCard(jsonObject.getString("studentIdCard"));
        contractAllInfo.setStudentProvince(jsonObject.getString("studentPro"));
        contractAllInfo.setStudentCity(jsonObject.getString("studentCity"));
        contractAllInfo.setStudentBorough(jsonObject.getString("studentBor"));
        contractAllInfo.setStudentSchool(jsonObject.getString("studentSchool"));
        contractAllInfo.setStudentGrade(jsonObject.getString("studentGrade"));
        contractAllInfo.setStudentClass(jsonObject.getString("studentClass"));
        contractAllInfo.setStudentAddress(jsonObject.getString("studentLocate"));
        contractAllInfo.setStudentPostal(jsonObject.getString("studentLocateCode"));
        contractAllInfo.setStudentPhone(jsonObject.getString("studentphone"));
        contractAllInfo.setStudentSex(jsonObject.getString("studentSex"));
        contractAllInfo.setStudentMajorType(jsonObject.getString("studentExam"));
        //家长
        contractAllInfo.setParentName(jsonObject.getString("parentName"));
        contractAllInfo.setParentIDCard(jsonObject.getString("parentIdCard"));
        contractAllInfo.setParentPhone(jsonObject.getString("parentPhone"));

        //退费
        Map<String,Integer> tuifeimap = new HashedMap();
        JSONObject tuifeiJsonobj = jsonObject.getJSONObject("tuifei");
        Set<String> set =  tuifeiJsonobj.keySet();
        System.out.println(set);
        for(String str : set){
            tuifeimap.put(str,Integer.valueOf(tuifeiJsonobj.getString(str)));
        }
        contractAllInfo.setTuifei(tuifeimap);
        //论文和奖项
        JSONObject feiyong = jsonObject.getJSONObject("feiyong");
        Map<String,Integer> lwjx = new HashMap<>();
        lwjx.put("dissertation",Integer.valueOf(feiyong.getString("lunwen")));
        lwjx.put("prize",Integer.valueOf(feiyong.getString("jingsai")));
        contractAllInfo.setOtherFw(lwjx);

        //服务
       JSONArray fyarr = feiyong.getJSONArray("fyarr");
       Map<Integer,Integer> fw = new HashMap<>();
       for (int f =0 ; f<fyarr.size();f++){
           fw.put(Integer.valueOf(fyarr.getJSONObject(f).getString("typevalue")),
                   Integer.valueOf(fyarr.getJSONObject(f).getString("monery")));
       }
       contractAllInfo.setFw(fw);
       contractAllInfo.setToZhiYuan(jsonObject.getBoolean("tozy"));
       contractAllInfo.setFwYear(jsonObject.getString("fuwuyear"));
       contractAllInfo.setOpen_ticket(jsonObject.getString("invoice"));
       contractAllInfo.setFwTeacher(jsonObject.getString("serviceTeacher"));//服务老师
       contractAllInfo.setFwTeam(jsonObject.getString("serviceTeam"));//服务团队

       contractAllInfo.setReamark(jsonObject.getString("remark"));
       contractAllInfo.setSigningTeacher(jsonObject.getString("signTeam"));//签单老师

        return contractAllInfo;

    }

    //===短信=====================================

    /**发送短信通知签署
     *
     *
     * @param invoice_no
     * @param Parentphone
     * @param ParentName
     * @return
     */
    @RequestMapping(value = "/sendMessages.json",method = RequestMethod.POST)
    @Function("contract.contractInfo.sendMessages")
    public String userSign(String invoice_no,String Parentphone,String ParentName){
        String destPath = ConfigService.contractfile;

        InvoiceUtils invoiceUtils=new InvoiceUtils();
        try {
            invoiceUtils.pdfToImage(destPath+"/"+invoice_no+"/"+invoice_no+".pdf", destPath+"/"+invoice_no+"/", null, 196f, false);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("生成合同图片失败！");
            return "生成合同图片失败！请联系客服";
        }

        //真正发送短信
        String host = "http://m.51sdx.com";
        String path = "/sdx-inter/esign/notificationSign";
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("parentPhone", Parentphone);
        querys.put("parentName", ParentName);
        querys.put("invoiceNo", invoice_no);
        try {
            boolean responseSMS = invoiceUtils.doPostSMS(host, path, null, querys);
            if (!responseSMS) {
                return "短信发送失败，请重新通知签署！";
            }
            ;
        } catch (IOException e) {
            e.printStackTrace();
        }

        //保存短信记录
        String url = "http://m.51sdx.com/sdx-inter/contract/electronContract/?invoiceNo="+invoice_no;
        TDMsgMq msg = new TDMsgMq();
        msg.setContent("【圣达信教育】尊敬的客户"+ParentName+"，您好！您的一对一服务订单已生成电子合同，请尽快签署。合同链接："+url);
        msg.setCreateDate(new Date());
        msg.setPhone(Parentphone);
        msg.setType(3);
        msg.setSendState(1);
        sqlManager.insertTemplate(msg);

        //修改订单状态
        List<ContractInfo> orders = sqlManager.query(ContractInfo.class).andEq("invoice_no",invoice_no).select();

        if (orders.size()>1){
         return "合同号重复 发送短信失败!";
        }else {
            for (ContractInfo order:orders) {
                order.setHtStatus(1);
                order.setOptDate(new Date());
                sqlManager.updateTemplateById(order);
            }
        }
        return "通知成功!";
    }


}
